package com.kfm.web.ex;

import com.alibaba.fastjson2.JSON;
import com.kfm.common.domain.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
@Slf4j
public class FileUploadExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        if (ex instanceof MaxUploadSizeExceededException exceededException) {
            log.info("处理文件上传的异常");
            if (ex.getCause().getCause() instanceof FileSizeLimitExceededException sizeLimitExceededException) {
                // 处理文件上传大小超限异常
                long maxFileSize = sizeLimitExceededException.getPermittedSize();
                long actualFileSize = sizeLimitExceededException.getActualSize();
                // 返回自定义响应
                // 将字节转换为兆字节
                double maxFileSizeInMB = maxFileSize / (1024.0 * 1024.0);
                double actualFileSizeInMB = actualFileSize / (1024.0 * 1024.0);

                // 格式化成字符串
                String errorMessage = String.format(
                        "文件大小超出限制。最大允许大小为 %.2f MB， 实际大小为 %.2f MB。",
                        maxFileSizeInMB,
                        actualFileSizeInMB
                );
                Result result = Result.failure(errorMessage);
                // 在实际应用中，可以考虑使用 ObjectMapper 将对象转为 JSON 格式
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                try {
                    response.getWriter().write(JSON.toJSONString(result));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // 返回一个空的 ModelAndView，表示异常已被处理
            return new ModelAndView();
        }
        // 返回 null 以让其他的异常处理器处理
        return null;
    }
}

